<?php
namespace app\index\controller;
use EasyWeChat\Factory;
use think\facade\Request;
use think\facade\Config;

// app 接口端
class Api extends Base
{

  private $config = [
    'app_id' => '',
    'secret' => '',

    // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
    'response_type' => 'array',
    
    //...
  ];

  public function initialize()
  {
    $this->config['app_id'] = config('appid');
    $this->config['secret'] = config('app_secret');
  }

  // 上传文件
  public function uploadFile()
  {
      // 获取表单上传文件 例如上传了001.jpg
      $file = request()->file('file');
      // 移动到框架应用根目录/uploads/ 目录下
      $info = $file->move('uploads');
      if($info){
          $fileName = str_replace('\\', '/',$info->getSaveName());
          return apiSuccess(config('file_url').'/uploads/'.$fileName);
      }else{
          // 上传失败获取错误信息
          // return apiError('文件格式有误');
          echo $file->getError();
      }
  }

   // 微信授权登录 或者是绑定微信
  public function authLogin() {
    $param = Request::param();
    $app = Factory::miniProgram($this->config);
    $res = $app->auth->session($param['code']);
    $userModel = model('user');
    $token = $userModel->login($res['openid']);
    return apiSuccess(['token'=>$token]); 
  }

  // 获取祝福语
  public function benediction() {
    $info = model('phrase')->orderRaw('rand()')->limit(1)->find();
    return apiSuccess($info); 
  }

  // 获取天气预报
  public function getWeather() {
    $name = 'clear_day.png';
    return apiSuccess($name); 
  }

  // 获取我的账本列表
  public function getUserBook() {
    $param = Request::param();
    $bookModel = model('book');
    $list = $bookModel->where(['user_id'=>$param['user_id']])->select();
    return apiSuccess($list); 
  }

  // 获取账本详情
  public function getBookInfo() {
    $param = Request::param();
    $bookModel = model('book');
    $info = $bookModel->where(['id'=>$param['id']])->find();
    return apiSuccess($info); 
  }

  // 添加修改账本
  public function setBookEdit() {
    $param = Request::param();
    $bookModel = model('book');
    $data = [
      'name' => $param['name'],
      'sort' => $param['sort']
    ];
    if(isset($param['id']) && !empty($param['id'])) {
      $bookModel->where(['id'=>$param['id']])->update($data);
    } else {
      $data['user_id'] = $param['user_id'];
      $bookModel->save($data);
    }
    return apiSuccess(); 
  }

  // 根据指定时间 和 账单 获取 收入 支出 不计收支 的统计 
  public function getTallyMainTotal() {
    $param = Request::param();
    $mainModel = model('main')->where(['user_id'=>$param['user_id']]);
    if(isset($param['book_id']) && !empty($param['book_id'])){
      $mainModel = $mainModel->where(['book_id'=>$param['book_id']]);
    }
    if( (isset($param['start_time']) && !empty($param['start_time'])) && (isset($param['end_time']) && !empty($param['end_time'])) ) {
      $mainModel = $mainModel->whereTime('date', 'between', [$param['start_time'], $param['end_time']]);
    }
    $list = $mainModel->select();
    $data = [
      'expend' => 0,
      'income' => 0,
      'disregard' => 0
    ];
    foreach ($list as $key => $value) {
      if($value['type'] == 1){
        $data['expend'] =  $data['expend']+$value['money'];
      }
      if($value['type'] == 2){
        $data['income'] =  $data['income']+$value['money'];
      }
      if($value['type'] == 3){
        $data['disregard'] =  $data['disregard']+$value['money'];
      }
    }
    
    return apiSuccess($data); 
  }

  // 获取账单列表
  public function getTallyMainList() {
    $param = Request::param();
    $mainModel = model('main')->with(['bookInfo', 'categoryInfo'])->where(['user_id'=>$param['user_id']]);
    if(isset($param['book_id']) && !empty($param['book_id'])){
      $mainModel = $mainModel->where(['book_id'=>$param['book_id']]);
    }
    if(isset($param['type']) && !empty($param['type'])){
      $mainModel = $mainModel->where(['type'=>$param['type']]);
    }
    
    if( (isset($param['start_time']) && !empty($param['start_time'])) && (isset($param['end_time']) && !empty($param['end_time'])) ) {
      $mainModel = $mainModel->whereTime('date', 'between', [$param['start_time'], $param['end_time']]);
    }
    $list = $mainModel->select();
    return apiSuccess($list); 
  }

  // 获取我的个人信息
  public function getUserInfo() {
    $param = Request::param();
    $info = model('user')->where(['id'=>$param['user_id']])->find();
    return apiSuccess($info); 
  }

  // 更新个人信息
  public function setUserInfo() {
    $param = Request::param();
    $data = [
      'nick_name' => $param['nick_name'],
      'sex' => $param['sex'],
      'job' => $param['job'],
      'avatar_url' => $param['avatar_url']
    ];
    $info = model('user')->where(['id'=>$param['id']])->update($data);
    return apiSuccess($info); 
  }

  // 获取分类列表
  public function getCategoryList() {
    $param = Request::param();
    $user_id = $param['user_id'];
    $query = model('category');

    if(isset($param['type']) && !empty($param['type'])){
      $query =  $query->where(['type'=>$param['type']]);
    }
    

    $list = $query->where(['type'=>$param['type'], 'is_del'=>1])->where(function ($query) use ($user_id) {
        $query->whereOr([
            ['user_id', '=', 0],
            ['user_id', '=', $user_id]
        ]);
    })->select();
    return apiSuccess($list); 
  }

  // 添加修改分类
  public function setCategoryEdit() {
    $param = Request::param();
    $categoryModel = model('category');
    $data = [
      'name' => $param['name'],
      'type' => $param['type'],
    ];

    if(empty($param['name'])) {
      return apiError('你居然想跳过？直接请求接口？');
    }
    if(isset($param['id']) && !empty($param['id'])) {
      $categoryModel->where(['id'=>$param['id']])->update($data);
    } else {
      $data['user_id'] = $param['user_id'];
      $data['icon_url'] = config('file_url').'/static/imgs/mot1.png';
      $categoryModel->save($data);
    }
    return apiSuccess(); 
  }

  // 添加修改 记账信息
  public function setTallyMainEdit() {
    $param = Request::param();
    $mainModel = model('main');
    $data = [
      'book_id' => $param['book_id'],
      'category_id' => $param['category_id'],
      'type' => $param['type'],
      'money' => $param['money'],
      'name' => $param['name'],
      'desc' => $param['desc'],
      'date' => $param['date']
    ];

    if(empty($param['book_id']) || empty($param['category_id']) || empty($param['type']) || empty($param['money']) || empty($param['name']) || empty($param['date'])) {
      return apiError('缺少参数');
    }

    if(isset($param['id']) && !empty($param['id'])) {
      $mainModel->where(['id'=>$param['id']])->update($data);
    } else {
      $data['user_id'] = $param['user_id'];
      $mainModel->save($data);
    }
    return apiSuccess(); 
  }

  // 获取记账信息
  public function getTallyMainInfo() {
    $param = Request::param();
    $mainModel = model('main');
    $info = $mainModel->where(['user_id'=>$param['user_id'], 'id'=>$param['id'], 'is_del'=>1])->find();
    return apiSuccess($info); 
  }








}
